//
//  WordErrorViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/28.
//

#import "WordErrorViewController.h"
#import "WordErrorCell.h"
#import "UITextView+Placeholder.h"
#import "FeedbackManager.h"
#import "FeedbackModel.h"
#import "FeedbackListModel.h"
#import "FeedbackAddManager.h"
#import "FeedbackAddSucceedView.h"

@interface WordErrorViewController ()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UITextView *textView;
@property(nonatomic,strong)FeedbackManager *feedbackManager;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,strong)UIButton *commitBtn;
@property(nonatomic,strong)NSMutableArray *selArr;
@property(nonatomic,strong)FeedbackAddManager *feedbackAddManager;
@property(nonatomic,strong)FeedbackAddSucceedView *succeedView;
@property(nonatomic,strong)UIImageView *topImageView;
@property(nonatomic,strong)UIView *footerView;
@property(nonatomic,strong)UIView *bgView;

@end

@implementation WordErrorViewController

-(FeedbackManager *)feedbackManager{
    if(!_feedbackManager){
        _feedbackManager = [[FeedbackManager alloc]init];
        _feedbackManager.delegate = self;
    }
    return _feedbackManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSMutableArray *)selArr{
    if(!_selArr){
        _selArr = [NSMutableArray array];
    }
    return _selArr;
}

-(FeedbackAddManager *)feedbackAddManager{
    if(!_feedbackAddManager){
        _feedbackAddManager = [[FeedbackAddManager alloc]init];
        _feedbackAddManager.delegate = self;
    }
    return _feedbackAddManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    [self loadData];
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor clearColor];
    [self.customNavigationBar setTitle:@"报错"];
    self.view.backgroundColor = UIColorHex(0xF2F7F6);
    CGFloat h636 = [DeviceUtils getAdaptedWidthForDesignWidth:636 andCurrentAvailableWidth:self.currentAvailableWidth];
    if(h636 > self.currentAvailableHeight){
        h636 = self.currentAvailableHeight;
    }
    UIImageView *topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,h636)];
    topImageView.image = [UIImage imageNamed:@"word_error_top_bg"];
    [self.view addSubview:topImageView];
    self.topImageView = topImageView;
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = JPUIFontNotoSansJPMedium(32);
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.text = self.wordModel.writing;
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@20);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+16);
        make.height.mas_equalTo(@45);
        make.right.mas_equalTo(@-20);
    }];
    
    __weak typeof(self)weakSelf = self;
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.font = JPUIFontPingFangBold(14);
    tipLabel.textColor = UIColorHex(0xFE4A4B);
    tipLabel.text = @"请选择报错原因";
    [self.view addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@20);
        make.top.mas_equalTo(weakSelf.titleLabel.mas_bottom).offset(10);
        make.height.mas_equalTo(@20);
        make.right.mas_equalTo(@-20);
    }];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(16,kYM_NAVIGATIONBAR_HEIGHT+ 107,self.currentAvailableWidth-32,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-107) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 45;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"WordErrorCell") forCellReuseIdentifier:@"WordErrorCell"];
    [self.view addSubview:self.tableView];
    
    CGFloat h49 = isIPAD?49:kWFit(49);
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth-32,117+20+h49+20)];
    footerView.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth-32,117)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [footerView addSubview:bgView];
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(16,16,self.currentAvailableWidth-64,85)];
    self.textView.backgroundColor = [UIColor whiteColor];
    self.textView.font = JPUIFontPingFangSCRegular(15);
    self.textView.textColor = KFontGrayColor;
    self.textView.tintColor = KThemeColor;
    [self.textView setPlaceholder:@"请对报错原因添加描述(必填)～" placeholdColor:KFontGrayColor];
    self.textView.contentInset = UIEdgeInsetsZero;
    self.textView.textContainerInset = UIEdgeInsetsZero;
    [bgView addSubview:self.textView];
    self.bgView = bgView;
    
    self.commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(bgView.frame)+20,self.currentAvailableWidth-32,kWFit(49))];
    if(isIPAD){
        self.commitBtn.frame = CGRectMake(0,CGRectGetMaxY(bgView.frame)+20,self.currentAvailableWidth-32,49);
    }
    [self.commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.commitBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    self.commitBtn.backgroundColor = UIColorHex(0xCCCCCC);
    if(isIPAD){
        self.commitBtn.layer.cornerRadius = 49/2.0;
    }else{
        self.commitBtn.layer.cornerRadius = kWFit(49)/2.0;
    }
    self.commitBtn.layer.masksToBounds = YES;
    self.commitBtn.ym_acceptEventInterval = 2.0;
    [self.commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.commitBtn];
    self.footerView = footerView;
    self.tableView.tableFooterView = footerView;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeText:) name:UITextViewTextDidChangeNotification object:self.textView];

    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth, kYM_NAVIGATIONBAR_HEIGHT);
            CGFloat h636 = [DeviceUtils getAdaptedWidthForDesignWidth:636 andCurrentAvailableWidth:self.currentAvailableWidth];
            if(h636 > self.currentAvailableHeight){
                h636 = self.currentAvailableHeight;
            }
            self.topImageView.frame = CGRectMake(0, 0, self.currentAvailableWidth,h636);
            self.tableView.frame =  CGRectMake(16,kYM_NAVIGATIONBAR_HEIGHT+ 107,self.currentAvailableWidth-32,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-107);
            [self.tableView reloadData];
            CGFloat h49 = isIPAD?49:kWFit(49);
            self.footerView.frame = CGRectMake(0, 0, self.currentAvailableWidth-32,117+20+h49+20);
            self.bgView.frame = CGRectMake(0, 0, self.currentAvailableWidth-32,117);
            self.textView.frame = CGRectMake(16,16,self.currentAvailableWidth-64,85);
            self.commitBtn.frame = CGRectMake(0,CGRectGetMaxY(self.bgView.frame)+20,self.currentAvailableWidth-32,49);
            self.tableView.tableFooterView = self.footerView;
            if(self.succeedView){
                self.succeedView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.currentAvailableHeight);
                self.succeedView.currentAvailableWidth = self.currentAvailableWidth;
                self.succeedView.currentAvailableHeight = self.currentAvailableHeight;
                [self.succeedView refreshWidth];
            }
        });
    }
}

#pragma mark - 获取错误反馈数据
-(void)loadData{
    [self.feedbackManager loadData];
}

#pragma mark - 提交
-(void)commitBtnClick{
    if(self.textView.text.length > 0){
        if(self.selArr.count == 0){
            [JPProgressHUD showMsg:@"请选择报错原因"];
            return;
        }
        NSMutableString *str = [NSMutableString string];
        for(NSInteger i = 0;i < self.selArr.count;i++){
            NSString *str2 = self.selArr[i];
            [str appendString:str2];
            if(i < self.selArr.count-1){
                [str appendString:@","];
            }
        }
        self.feedbackAddManager.memo = self.textView.text;
        self.feedbackAddManager.option1 = str;
        self.feedbackAddManager.wordId = self.wordModel.wordId;
        [self.feedbackAddManager loadData];
    }
}

#pragma mark - 提交成功弹窗
-(void)showSuccessView{
    if(!self.succeedView){
        self.succeedView = [[FeedbackAddSucceedView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth, self.currentAvailableHeight)];
    }
    self.succeedView.currentAvailableWidth = self.currentAvailableWidth;
    self.succeedView.currentAvailableHeight = self.currentAvailableHeight;
    if(KEY_WINDOW){
        [KEY_WINDOW addSubview:self.succeedView];
        __weak typeof(self)weakSelf = self;
        [self.succeedView setCloseBlock:^{
            [weakSelf.succeedView removeFromSuperview];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }
}

#pragma mark - 监测用户输入文本长度
- (void)textViewDidChangeText:(NSNotification *)notification{
    
    //最大输入长度,中英文字符都按一个字符计算
    static int kMaxLength = 20;
    UITextView *textView = (UITextView *)notification.object;
    NSString *toBeString = textView.text;
    // 获取键盘输入模式
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    // 中文输入的时候,可能有markedText(高亮选择的文字),需要判断这种状态
    // zh-Hans表示简体中文输入, 包括简体拼音，健体五笔，简体手写
    if ([lang isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textView markedTextRange];
        //获取高亮选择部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，表明输入结束,则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > kMaxLength) {
                // 截取子串
                textView.text = [toBeString substringToIndex:kMaxLength];
            }
        }
    } else {
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > kMaxLength) {
            // 截取子串
            textView.text = [toBeString substringToIndex:kMaxLength];
        }
    }
    if(textView.text.length > 0){
        self.commitBtn.backgroundColor = KThemeColor;
    }else{
        self.commitBtn.backgroundColor = UIColorHex(0xCCCCCC);
    }
}


#pragma mark - tableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WordErrorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WordErrorCell"];
    FeedbackModel *model = self.dataArr[indexPath.section];
    if(indexPath.row < model.list.count){
        FeedbackListModel *listModel = model.list[indexPath.row];
        cell.model = listModel;
        NSString *str = [NSString stringWithFormat:@"%@-%@",model.name,listModel.dictDataName];
        if([self.selArr containsObject:str]){
            cell.isSel = YES;
        }else{
            cell.isSel = NO;
        }
    }
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    FeedbackModel *model = self.dataArr[section];
    return model.list.count;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat w = self.currentAvailableWidth-32;
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0,0,w,50.5)];
    headView.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,0,w,50.5)];
    bgView.backgroundColor = [UIColor whiteColor];
    [headView addSubview:bgView];
    [bgView addRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadii:CGSizeMake(10,10)];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(16,16,w-32-26,22)];
    titleLabel.font = JPUIFontPingFangSCMedium(16);
    titleLabel.textColor = KFontBlackColor;
    if(section < self.dataArr.count){
        FeedbackModel *model = self.dataArr[section];
        titleLabel.text = model.name;
    }
    [bgView addSubview:titleLabel];
    UIImageView *downImageView = [[UIImageView alloc]initWithFrame:CGRectMake(w-32,19,16,16)];
    downImageView.image = [UIImage imageNamed:@"word_error_down"];
    [headView addSubview:downImageView];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.5;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat w = self.currentAvailableWidth-32;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,w,25.5)];
    footerView.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0,-0.5,w,14)];
    bgView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:bgView];
    [bgView addRoundedCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight withRadii:CGSizeMake(10,10)];
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 25.5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section < self.dataArr.count){
        FeedbackModel *model = self.dataArr[indexPath.section];
        if(indexPath.row < model.list.count){
            FeedbackListModel *listModel = model.list[indexPath.row];
            NSString *str = [NSString stringWithFormat:@"%@-%@",model.name,listModel.dictDataName];
            if([self.selArr containsObject:str]){
                [self.selArr removeObject:str];
            }else{
                [self.selArr addObject:str];
            }
            [self.tableView reloadData];
        }
    }
}


#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    if([manager isEqual:self.feedbackManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [FeedbackModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        for(NSInteger i = 0;i < arr.count;i++){
            FeedbackModel *model = arr[i];
            NSArray *list = [FeedbackListModel mj_objectArrayWithKeyValuesArray:model.list];
            model.list = list;
            [self.dataArr addObject:model];
        }
        [self.tableView reloadData];
    }
    
    if([manager isEqual:self.feedbackAddManager]){
        [self showSuccessView];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
